// pages/evaluatedEffect/index.js
const api = require('../../config/api')
const request = require('../../utils/request')
const { swapArray } = require('./../../utils/util')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showList: [],
    hideList: [],
    itemheight: 50,
    jiange: 0,
    jianqu: 0,
    nowmoveindex: -1,
    movetop: 0,
    moveoutindex: -1,
    switchChecked: true,
  },

  onLoad: function () {
    this.getwxmlcode('#movebox', (resp) => {
      this.setData({ movebox: resp })
      setTimeout(() => {
        this.getwxmlcode('#movelist0', (res) => {
          if (res) {
            this.setData({ movelist0: res })
            var jiange = res.top - resp.top
            var yiban = res.bottom - res.top + jiange
            this.setData({
              itemheight: res.bottom - res.top,
              jiange: yiban, //两条中间到另一条的距离
              jianqu: resp.top - (res.bottom - res.top) / 2, //位置要减去距离
            })
          }
        })
      }, 300)
    })
    this.getConfigList()
  },
  // 用户设置展示列表
  async getConfigList() {
    const patientInfo = wx.getStorageSync('patientInfo')
    let res = await request.get(
      api.chartConfigList,
      {
        patientId: Number(patientInfo.id),
      },
      { loading: false }
    )

    if (res.httpStatus === 200) {
      let showArr = []
      let hideArr = []

      res.data.map((item) => {
        // isExhibition 是否展示（0,不展示；1，展示）
        if (item.isExhibition === 1) {
          showArr.push(item)
        } else {
          hideArr.push(item)
        }
      })
      this.setData({
        showList: showArr,
        hideList: hideArr,
      })
    }
  },
  getwxmlcode(str, cal) {
    const query1 = wx.createSelectorQuery()
    query1.select(str).boundingClientRect()
    query1.selectViewport().scrollOffset()
    query1.exec((res) => {
      if (cal) cal(res[0])
    })
  },
  listItemMove(e) {
    let { switchChecked } = this.data
    if (!switchChecked) {
      return
    }
    if (e.type == 'touchmove') {
      var movetop = e.touches[0].pageY - this.data.itemheight
      var moveoutindex = parseInt(
        (movetop - this.data.jianqu) / this.data.jiange
      )
      if (e.currentTarget.dataset.index <= moveoutindex) moveoutindex++
      this.moveoutindex = moveoutindex
      this.setData({
        nowmoveindex: e.currentTarget.dataset.index,
        movetop,
        moveoutindex,
      })
    } else {
      let index = e.currentTarget.dataset.index,
        score = this.data.showList
      let data = { ...score[index] }
      score.splice(index, 1)
      if (index <= this.moveoutindex - 1) this.moveoutindex--
      score.splice(this.moveoutindex, 0, data)
      this.setData({ showList: score, moveoutindex: -1, nowmoveindex: -1 })
      this.handleOperate()
    }
  },
  handleUp(e){
    let { switchChecked } = this.data
    if (!switchChecked) {
      return
    }
    let index = e.currentTarget.dataset.index,
        score = this.data.showList
    let data = { ...score[index] }
    if(index != 0){
        swapArray(score, index, index-1);
    }else{
        console.log('已经处于置顶，无法上移');
    }
    wx.vibrateShort({
      type: 'light',
    })
    this.setData({ showList: score })
    this.handleOperate()
  },
  
  // 开关
  async switchChange(e) {
    const patientInfo = wx.getStorageSync('patientInfo')
    const res = await request.post(
      api.displaySetting,
      {
        isShowTrendChart: e.detail.value ? 1 : 0,
        patientId: Number(patientInfo.id),
      },
      { loading: false }
    )
    if (res.httpStatus === 200) {
      this.setData({
        switchChecked: e.detail.value,
      })
    }
  },
  // 增加
  handleAdd(val) {
    let { showList, hideList, switchChecked } = this.data
    if (!switchChecked) {
      return
    }
    let obj = val.currentTarget.dataset.item
    hideList.splice(
      hideList.findIndex((item) => item.id === obj.id),
      1
    )
    this.setData({
      showList: showList.concat(obj),
      hideList: hideList,
    })
    this.handleOperate()
  },
  // 取消
  handleCancle(val) {
    let { showList, hideList, switchChecked } = this.data
    if (!switchChecked) {
      return
    }
    let obj = val.currentTarget.dataset.item
    showList.splice(
      showList.findIndex((item) => item.id === obj.id),
      1
    )
    this.setData({
      hideList: hideList.concat(obj),
      showList: showList,
    })
    this.handleOperate()
  },
  // 获取患者详情
  getPatientDetial: async function () {
    const patientInfo = wx.getStorageSync('patientInfo')
    const res = await request.get(
      api.patientDetail + '/' + patientInfo.id,
      {},
      { loading: false }
    )
    if (res.httpStatus === 200) {
      this.setData({
        switchChecked: res.data.isShowTrendChart === 1,
      })
    }
  },
  // 每操作一步之后请求
  async handleOperate() {
    let { showList, hideList } = this.data

    showList.map((item, index) => {
      item.isExhibition = 1
      return item
    })
    hideList.map((item, index) => {
      item.isExhibition = 0
      return item
    })
    let allList = [...showList, ...hideList]
    let requestList = []
    allList.map((item, index) => {
      let obj = {
        id: item.id,
        isExhibition: item.isExhibition,
        patientId: item.patientId,
        sort: index + 1,
      }
      requestList.push(obj)
    })
    const res = await request.post(
      api.chartConfigSort,
      {
        chartConfigList: requestList,
      },
      { loading: false }
    )
    if (res.httpStatus === 200) {
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getPatientDetial()
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
})
